<?php

namespace App\Http\Controllers;

use App\Http\Requests\AuthRequests\EmailCodeRequest;
use App\Jobs\Service\EmailJob;
use App\Models\User;
use App\Services\Email;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Overtrue\EasySms\PhoneNumber;

class EmailController extends Controller
{
    /**
     * @param EmailCodeRequest $request
     * @param Email            $emailService
     *
     * @return Response
     */
    public function sendCode(EmailCodeRequest $request, Email $emailService)
    {
        $email = $request->input('email');
        if (!$email) {
            if (Auth::check()) {
                $email = Auth::user()->email;
            } else {
                $this->error(40001);
            }
        }

        $ip = $request->ip();

        $emailService->checkThrottle($ip, $email);

        if (app()->isLocal()) {
            Cache::put('email_code:' . $email, 123456, now()->addMinutes(15));
        } else {
//            $emailService->sendCode($email);
            //            EmailJob::dispatch($email)->onQueue('email_code');


            // 使用阿里云作为代理服务器，发送邮件
            $code = rand(111111, 999999); // 验证码
            $url='http://email.ethstar.vip/api/email';
            try {
                Cache::put('email_code:'.$email, $code, now()->addMinutes(15));
                $response = (new Client())->get($url, [
                    'query' => [
                        'email' => $email,
                        'code' => $code
                    ]
                ]);
                $re = json_decode($response->getBody()->getContents(),true);
                if( $re['code'] != 200 ) {
                    throw new \Exception($re['message']);
                }
            } catch (\Exception $exception) {
                logger('==========Email==========');
                logger($exception);
                $this->error(70000, $exception->getMessage());
            }
        }

        $emailService->setThrottle($ip, $email);

        return $this->null();
    }

    /**
     * 验证验证码.
     * @param Request $request
     * @return Response
     */
    public function codeCheck(Request $request)
    {
        $type = $request->query('type'); // 类型（1-邮箱 2-短信）
        $code = $request->query('code'); // 邮箱或短信验证码

        if (!in_array($type, [1, 2])) {
            $this->error(1011);
        }

        if (1 == $type) { // 邮箱
            $email = Auth::user()->email;
            if ($code && Cache::get('email_code:' . $email) == $code) {
                return $this->null();
            } else {
                $this->error(1009);
            }
        } else { // 手机
            /** @var User $user */
            $user = Auth::user();
            if ($code && Cache::get('sms_code:' . (new PhoneNumber($user->mobile, $user->area))->getUniversalNumber()) == $code) {
                return $this->null();
            } else {
                $this->error(1010);
            }
        }
    }
}
